import { NextResponse } from 'next/server'
import bcrypt from 'bcryptjs'
import prisma from '@/lib/prisma'
import { SignJWT } from 'jose'

const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET || 'your-secret-key')
// Convert milliseconds to seconds for JWT expiration
const JWT_EXPIRATION = process.env.JWT_EXPIRATION ? 
process.env.JWT_EXPIRATION: 
  '1h'

export async function POST(request: Request) {
  try {
    const { email, password } = await request.json()

    // Validate input
    if (!email || !password) {
      return NextResponse.json(
        { error: 'Email, password are required' },
        { status: 400 }
      )
    }

    // Check if user already exists
    const existingUser = await prisma.vms_user.findFirst({
      where: { email: email as string }
    })

    if (existingUser) {
      return NextResponse.json(
        { error: 'User already exists' },
        { status: 400 }
      )
    }

    // Hash password using bcrypt (same as original system)
    const hashedPassword = await bcrypt.hash(password, bcrypt.genSaltSync())

    // Create new user
    const newUser = await prisma.vms_user.create({
      data: {
        id: crypto.randomUUID(),
        email,
        password: hashedPassword,
        zcsj: new Date(),
        status: 'active',
        roles: 'user',
        ai_count: 0,
        copy_count: 0,
        script_count: 0,
        topic_count: 0,
        voice_count: 0,
        subtitle_count: 0,
        ai_count_limit: 100,
        copy_count_limit: 10,
        script_count_limit: 200*5,
        topic_count_limit: 2,
        voice_count_limit: 30,
        subtitle_count_limit: 2,
        vip_type: 'free',
        vip_end_time: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000),
      }
    })

    // Generate JWT token using jose
    const token = await new SignJWT({
      id: newUser.id,
      email: newUser.email,
      roles: newUser.roles,
      vip_type: newUser.vip_type,
      vip_end_time: newUser.vip_end_time?.toISOString()
    })
      .setProtectedHeader({ alg: 'HS256' })
      .setExpirationTime(JWT_EXPIRATION)
      .sign(JWT_SECRET)

    // Return success response with token and user data (without password)
    const { password: _, ...userWithoutPassword } = newUser
    return NextResponse.json(
      { 
        ...userWithoutPassword,
        token 
      }, 
      { status: 201 }
    )

  } catch (error) {
    console.error('Registration error:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}
